// 游戏核心逻辑
        class CangjieGame {
            constructor() {
                this.currentLevel = 1;
                this.score = 0;
                this.hints = 3;
                this.timeLeft = 120;
                this.timer = null;
                this.isPaused = false;
                this.isGameActive = false;
                this.currentCharacter = null;
                this.difficulty = 'medium';
                this.completedCharacters = [];
                
                // DOM元素
                this.levelElement = document.getElementById('level');
                this.scoreElement = document.getElementById('score');
                this.timerElement = document.getElementById('timer');
                this.hintsElement = document.getElementById('hints');
                this.targetCharacterElement = document.getElementById('target-character');
                this.characterMeaningElement = document.getElementById('character-meaning');
                this.targetGridElement = document.getElementById('target-grid');
                this.puzzlePiecesElement = document.getElementById('puzzle-pieces');
                this.messageElement = document.getElementById('message');
                this.legendTextElement = document.getElementById('legend-text');
                
                // 游戏控制按钮
                this.startBtn = document.getElementById('start-btn');
                this.pauseBtn = document.getElementById('pause-btn');
                this.hintBtn = document.getElementById('hint-btn');
                this.shuffleBtn = document.getElementById('shuffle-btn');
                this.resetBtn = document.getElementById('reset-btn');
                this.nextBtn = document.getElementById('next-btn');
                this.difficultySelect = document.getElementById('difficulty-select');
                
                // 初始化
                this.init();
            }
            
            init() {
                // 更新仓颉传说
                this.updateLegend();
                
                // 设置事件监听器
                this.setupEventListeners();
                
                // 初始化游戏
                this.resetGame();
            }
            
            setupEventListeners() {
                // 开始游戏按钮
                this.startBtn.addEventListener('click', () => {
                    this.startGame();
                });
                
                // 暂停游戏按钮
                this.pauseBtn.addEventListener('click', () => {
                    this.togglePause();
                });
                
                // 提示按钮
                this.hintBtn.addEventListener('click', () => {
                    this.useHint();
                });
                
                // 打乱按钮
                this.shuffleBtn.addEventListener('click', () => {
                    this.shufflePieces();
                });
                
                // 重置按钮
                this.resetBtn.addEventListener('click', () => {
                    this.resetCurrentLevel();
                });
                
                // 下一关按钮
                this.nextBtn.addEventListener('click', () => {
                    this.nextLevel();
                });
                
                // 难度选择
                this.difficultySelect.addEventListener('change', (e) => {
                    this.difficulty = e.target.value;
                    if (this.isGameActive) {
                        this.resetGame();
                    }
                });
                
                // 从游戏说明开始游戏
                const startFromInstructionsBtn = document.getElementById('start-from-instructions');
                if (startFromInstructionsBtn) {
                    startFromInstructionsBtn.addEventListener('click', () => {
                        this.closeModal('instructions-modal');
                        this.startGame();
                    });
                }
                
                // 重新开始按钮
                const restartBtn = document.getElementById('restart-btn');
                if (restartBtn) {
                    restartBtn.addEventListener('click', () => {
                        this.closeModal('game-over-modal');
                        this.resetGame();
                        this.startGame();
                    });
                }
                
                // 关闭模态框
                const closeModalButtons = document.querySelectorAll('.close-modal');
                closeModalButtons.forEach(button => {
                    button.addEventListener('click', () => {
                        const modalId = button.closest('.modal').id;
                        this.closeModal(modalId);
                    });
                });
                
                // 点击模态框外部关闭
                window.addEventListener('click', (e) => {
                    if (e.target.classList.contains('modal')) {
                        this.closeModal(e.target.id);
                    }
                });
                
                // 拖放功能
                this.setupDragAndDrop();
            }
            
            startGame() {
                if (this.isGameActive) return;
                
                this.isGameActive = true;
                this.isPaused = false;
                this.currentLevel = 1;
                this.score = 0;
                this.hints = 3;
                this.timeLeft = 120;
                this.completedCharacters = [];
                
                this.updateUI();
                this.startTimer();
                this.loadLevel();
                
                this.startBtn.disabled = true;
                this.pauseBtn.innerHTML = '<i class="fas fa-pause"></i> 暂停';
                this.showMessage("游戏开始！拼出正确的汉字进入下一关。", "success");
            }
            
            resetGame() {
                this.stopTimer();
                this.isGameActive = false;
                this.isPaused = false;
                this.currentLevel = 1;
                this.score = 0;
                this.hints = 3;
                this.timeLeft = 120;
                this.completedCharacters = [];
                
                this.updateUI();
                this.clearGameArea();
                this.startBtn.disabled = false;
                this.pauseBtn.innerHTML = '<i class="fas fa-pause"></i> 暂停';
            }
            
            startTimer() {
                this.stopTimer();
                this.timer = setInterval(() => {
                    if (!this.isPaused && this.isGameActive) {
                        this.timeLeft--;
                        this.timerElement.textContent = this.timeLeft;
                        
                        if (this.timeLeft <= 0) {
                            this.gameOver("时间到了！游戏结束。");
                        } else if (this.timeLeft <= 30) {
                            this.timerElement.style.color = "#e74c3c";
                            this.timerElement.style.fontWeight = "bold";
                        }
                    }
                }, 1000);
            }
            
            stopTimer() {
                if (this.timer) {
                    clearInterval(this.timer);
                    this.timer = null;
                }
            }
            
            togglePause() {
                if (!this.isGameActive) return;
                
                this.isPaused = !this.isPaused;
                
                if (this.isPaused) {
                    this.pauseBtn.innerHTML = '<i class="fas fa-play"></i> 继续';
                    this.showMessage("游戏已暂停", "error");
                } else {
                    this.pauseBtn.innerHTML = '<i class="fas fa-pause"></i> 暂停';
                    this.showMessage("游戏继续", "success");
                }
            }
            
            loadLevel() {
                if (!this.isGameActive) return;
                
                // 获取当前难度的汉字数据
                const levelData = charactersData[this.difficulty];
                
                // 确保不会重复选择同一个汉字
                let availableCharacters = levelData.filter(char => 
                    !this.completedCharacters.includes(char.character)
                );
                
                // 如果所有汉字都已完成，重新开始
                if (availableCharacters.length === 0) {
                    availableCharacters = levelData;
                    this.completedCharacters = [];
                }
                
                // 随机选择一个汉字
                const randomIndex = Math.floor(Math.random() * availableCharacters.length);
                this.currentCharacter = availableCharacters[randomIndex];
                
                // 更新UI
                this.targetCharacterElement.textContent = this.currentCharacter.character;
                this.characterMeaningElement.textContent = `(含义：${this.currentCharacter.meaning})`;
                
                // 创建目标网格
                this.createTargetGrid();
                
                // 创建拼图块
                this.createPuzzlePieces();
                
                // 更新关卡显示
                this.levelElement.textContent = this.currentLevel;
                
                // 更新仓颉传说
                this.updateLegend();
            }
            
            createTargetGrid() {
                this.targetGridElement.innerHTML = '';
                const gridSize = this.currentCharacter.gridSize;
                
                // 根据gridSize设置网格列数
                let gridCols = 3;
                if (gridSize === 1) gridCols = 1;
                else if (gridSize === 2) gridCols = 2;
                
                this.targetGridElement.style.gridTemplateColumns = `repeat(${gridCols}, 1fr)`;
                
                // 创建网格单元格
                for (let i = 0; i < gridSize * gridSize; i++) {
                    const cell = document.createElement('div');
                    cell.className = 'grid-cell';
                    cell.dataset.index = i;
                    this.targetGridElement.appendChild(cell);
                }
            }
            
            createPuzzlePieces() {
                this.puzzlePiecesElement.innerHTML = '';
                
                // 创建拼图块（包含正确的部件和一些干扰项）
                const allPieces = [...this.currentCharacter.components];
                
                // 添加一些干扰部件（根据难度）
                const distractors = this.getDistractorComponents();
                allPieces.push(...distractors);
                
                // 打乱顺序
                this.shuffleArray(allPieces);
                
                // 创建拼图块元素
                allPieces.forEach((piece, index) => {
                    const pieceElement = document.createElement('div');
                    pieceElement.className = 'puzzle-piece';
                    pieceElement.textContent = piece;
                    pieceElement.dataset.component = piece;
                    pieceElement.dataset.index = index;
                    pieceElement.draggable = true;
                    this.puzzlePiecesElement.appendChild(pieceElement);
                });
            }
            
            getDistractorComponents() {
                // 根据难度返回干扰部件
                const commonComponents = ["口", "人", "日", "月", "木", "水", "火", "土", "山", "石", "田", "子", "女", "心"];
                const distractors = [];
                
                // 随机选择干扰部件数量
                let distractorCount = 0;
                if (this.difficulty === 'easy') distractorCount = 2;
                else if (this.difficulty === 'medium') distractorCount = 4;
                else distractorCount = 6;
                
                // 过滤掉已经在正确部件中的部件
                const availableComponents = commonComponents.filter(comp => 
                    !this.currentCharacter.components.includes(comp)
                );
                
                // 随机选择干扰部件
                for (let i = 0; i < distractorCount && availableComponents.length > 0; i++) {
                    const randomIndex = Math.floor(Math.random() * availableComponents.length);
                    distractors.push(availableComponents[randomIndex]);
                    availableComponents.splice(randomIndex, 1);
                }
                
                return distractors;
            }
            
            setupDragAndDrop() {
                // 允许拖放
                document.addEventListener('dragstart', (e) => {
                    if (e.target.classList.contains('puzzle-piece') && 
                        !e.target.classList.contains('used') && 
                        !e.target.classList.contains('correct') &&
                        !this.isPaused && this.isGameActive) {
                        e.target.classList.add('dragging');
                        e.dataTransfer.setData('text/plain', e.target.dataset.component);
                        e.dataTransfer.setData('index', e.target.dataset.index);
                    }
                });
                
                document.addEventListener('dragend', (e) => {
                    if (e.target.classList.contains('puzzle-piece')) {
                        e.target.classList.remove('dragging');
                    }
                });
                
                // 允许放置
                this.targetGridElement.addEventListener('dragover', (e) => {
                    e.preventDefault();
                });
                
                this.targetGridElement.addEventListener('drop', (e) => {
                    e.preventDefault();
                    if (this.isPaused || !this.isGameActive) return;
                    
                    const component = e.dataTransfer.getData('text/plain');
                    const pieceIndex = e.dataTransfer.getData('index');
                    const cell = e.target.closest('.grid-cell');
                    
                    if (!cell || cell.classList.contains('filled')) return;
                    
                    // 获取拼图块元素
                    const pieceElement = document.querySelector(`.puzzle-piece[data-index="${pieceIndex}"]`);
                    if (!pieceElement || pieceElement.classList.contains('used')) return;
                    
                    // 检查放置位置是否正确
                    const cellIndex = parseInt(cell.dataset.index);
                    const correctComponents = this.currentCharacter.components;
                    
                    // 简单验证：检查部件是否是目标汉字的一部分
                    if (correctComponents.includes(component)) {
                        // 放置正确
                        cell.textContent = component;
                        cell.classList.add('filled');
                        pieceElement.classList.add('used', 'correct');
                        
                        // 增加分数
                        this.addScore(10);
                        
                        // 检查是否完成
                        this.checkCompletion();
                    } else {
                        // 放置错误
                        cell.style.backgroundColor = "#f8d7da";
                        cell.style.borderColor = "#f5c6cb";
                        cell.textContent = "×";
                        
                        setTimeout(() => {
                            cell.style.backgroundColor = "";
                            cell.style.borderColor = "";
                            cell.textContent = "";
                        }, 500);
                        
                        this.showMessage("这个部件不属于这个汉字", "error");
                    }
                });
            }
            
            checkCompletion() {
                const filledCells = document.querySelectorAll('.grid-cell.filled');
                const correctComponents = this.currentCharacter.components;
                
                // 检查是否所有正确部件都已放置
                const placedComponents = Array.from(filledCells).map(cell => cell.textContent);
                const allCorrectPlaced = correctComponents.every(comp => placedComponents.includes(comp));
                
                if (allCorrectPlaced && filledCells.length >= correctComponents.length) {
                    // 完成当前关卡
                    this.completeLevel();
                }
            }
            
            completeLevel() {
                // 增加分数
                this.addScore(50);
                
                // 记录已完成的汉字
                this.completedCharacters.push(this.currentCharacter.character);
                
                // 显示完成消息
                this.showMessage(`恭喜！你成功拼出了"${this.currentCharacter.character}"！`, "success");
                
                // 禁用拼图块
                const pieces = document.querySelectorAll('.puzzle-piece');
                pieces.forEach(piece => {
                    piece.classList.add('used');
                    piece.draggable = false;
                });
                
                // 等待1秒后进入下一关
                setTimeout(() => {
                    this.nextLevel();
                }, 1000);
            }
            
            nextLevel() {
                if (!this.isGameActive) return;
                
                this.currentLevel++;
                this.loadLevel();
                this.showMessage(`第${this.currentLevel}关开始！`, "success");
            }
            
            resetCurrentLevel() {
                if (!this.isGameActive || this.isPaused) return;
                
                // 清空目标网格
                const cells = document.querySelectorAll('.grid-cell');
                cells.forEach(cell => {
                    cell.textContent = '';
                    cell.classList.remove('filled');
                });
                
                // 重置拼图块
                const pieces = document.querySelectorAll('.puzzle-piece');
                pieces.forEach(piece => {
                    piece.classList.remove('used', 'correct');
                    piece.draggable = true;
                });
                
                this.showMessage("当前关卡已重置", "error");
            }
            
            useHint() {
                if (!this.isGameActive || this.isPaused || this.hints <= 0) return;
                
                // 减少提示次数
                this.hints--;
                this.hintsElement.textContent = this.hints;
                document.getElementById('hint-btn').innerHTML = `<i class="fas fa-lightbulb"></i> 提示 (剩余: ${this.hints})`;
                
                // 减少分数
                this.addScore(-20);
                
                // 找到一个未放置的正确部件并高亮显示
                const correctComponents = this.currentCharacter.components;
                const pieces = document.querySelectorAll('.puzzle-piece:not(.used)');
                let hintGiven = false;
                
                for (let piece of pieces) {
                    if (correctComponents.includes(piece.dataset.component) && !hintGiven) {
                        // 高亮显示这个部件
                        piece.style.backgroundColor = "#fff3cd";
                        piece.style.border = "2px solid #ffc107";
                        piece.style.color = "#856404";
                        
                        // 3秒后取消高亮
                        setTimeout(() => {
                            piece.style.backgroundColor = "";
                            piece.style.border = "";
                            piece.style.color = "";
                        }, 3000);
                        
                        hintGiven = true;
                        this.showMessage("一个正确的部件已被高亮显示", "success");
                        break;
                    }
                }
                
                if (!hintGiven) {
                    this.showMessage("没有可用的提示", "error");
                }
            }
            
            shufflePieces() {
                if (!this.isGameActive || this.isPaused) return;
                
                const piecesContainer = this.puzzlePiecesElement;
                const pieces = Array.from(piecesContainer.children);
                
                // 打乱顺序
                this.shuffleArray(pieces);
                
                // 重新添加到容器
                pieces.forEach(piece => {
                    piecesContainer.appendChild(piece);
                });
                
                this.showMessage("拼图块已打乱", "success");
            }
            
            shuffleArray(array) {
                for (let i = array.length - 1; i > 0; i--) {
                    const j = Math.floor(Math.random() * (i + 1));
                    [array[i], array[j]] = [array[j], array[i]];
                }
                return array;
            }
            
            addScore(points) {
                this.score += points;
                if (this.score < 0) this.score = 0;
                this.scoreElement.textContent = this.score;
                
                // 添加分数变化动画
                this.scoreElement.style.transform = 'scale(1.2)';
                this.scoreElement.style.color = points > 0 ? '#2ecc71' : '#e74c3c';
                
                setTimeout(() => {
                    this.scoreElement.style.transform = 'scale(1)';
                    this.scoreElement.style.color = '#3a7bd5';
                }, 300);
            }
            
            gameOver(reason) {
                this.stopTimer();
                this.isGameActive = false;
                
                // 计算最终得分（加上剩余时间）
                const timeBonus = Math.floor(this.timeLeft);
                this.addScore(timeBonus);
                
                // 显示游戏结束模态框
                const gameOverContent = document.getElementById('game-over-content');
                gameOverContent.innerHTML = `
                    <p>${reason}</p>
                    <p>最终得分: <strong>${this.score}</strong></p>
                    <p>完成关卡: <strong>${this.currentLevel - 1}</strong></p>
                    <p>剩余时间奖励: <strong>+${timeBonus}</strong> 分</p>
                    <p>使用的提示: <strong>${3 - this.hints}</strong> 次</p>
                `;
                
                this.showModal('game-over-modal');
            }
            
            updateUI() {
                this.levelElement.textContent = this.currentLevel;
                this.scoreElement.textContent = this.score;
                this.timerElement.textContent = this.timeLeft;
                this.hintsElement.textContent = this.hints;
                
                // 重置计时器颜色
                this.timerElement.style.color = '#3a7bd5';
                this.timerElement.style.fontWeight = 'normal';
                
                // 更新提示按钮文本
                document.getElementById('hint-btn').innerHTML = `<i class="fas fa-lightbulb"></i> 提示 (剩余: ${this.hints})`;
            }
            
            updateLegend() {
                // 随机选择一个仓颉传说
                const randomIndex = Math.floor(Math.random() * cangjieLegends.length);
                this.legendTextElement.textContent = cangjieLegends[randomIndex];
            }
            
            clearGameArea() {
                this.targetGridElement.innerHTML = '';
                this.puzzlePiecesElement.innerHTML = '';
                this.targetCharacterElement.textContent = '';
                this.characterMeaningElement.textContent = '';
                this.hideMessage();
            }
            
            showMessage(text, type) {
                this.messageElement.textContent = text;
                this.messageElement.className = `message ${type}`;
                
                // 3秒后隐藏消息
                setTimeout(() => {
                    this.hideMessage();
                }, 3000);
            }
            
            hideMessage() {
                this.messageElement.style.display = 'none';
                this.messageElement.className = 'message';
            }
            
            showModal(modalId) {
                const modal = document.getElementById(modalId);
                if (modal) {
                    modal.style.display = 'flex';
                }
            }
            
            closeModal(modalId) {
                const modal = document.getElementById(modalId);
                if (modal) {
                    modal.style.display = 'none';
                }
            }
        }